package com.netty.demo.utils;

import com.netty.demo.protocol.packet.LoginRequestPacket;
import com.netty.demo.protocol.packet.MessagePacket;
import com.netty.demo.protocol.packet.PacketCodec;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;

import java.util.Date;
import java.util.Scanner;

public class ConsoleUtils {
    public static void startClientConsoleThread(Channel channel){
        new Thread(() -> {
            while (!Thread.interrupted()) {
                if (LoginUtils.hasLogin(channel)) {
                    System.out.print("输入消息发送至服务端: ");
                    Scanner sc = new Scanner(System.in);
                    String line = sc.nextLine();

                    MessagePacket packet = new MessagePacket();
                    packet.setMessage(line);
                    packet.setSendTime(new Date());
                    packet.setUserId(LoginUtils.getLoginUserId(channel));
                    channel.writeAndFlush(packet);
                } else {
//                    LoginRequestPacket loginRequestPacket = new LoginRequestPacket();
//                    System.out.print("登录名: ");
//                    Scanner sc = new Scanner(System.in);
//                    String line = sc.nextLine();
//                    loginRequestPacket.setUserId(LoginUtils.createUserId());
//                    loginRequestPacket.setUsername(line);
//                    System.out.print("密码: ");
//                    sc = new Scanner(System.in);
//                    line = sc.nextLine();
//                    loginRequestPacket.setPassword(line);
//                    channel.writeAndFlush(loginRequestPacket);
//                    System.out.println("登录中...");
                }
            }
        }).start();
    }

    public static void startServerConsoleThread(){
        new Thread(() -> {
            while (!Thread.interrupted()) {
                System.out.println("输入消息发送至客户端: ");
                Scanner sc = new Scanner(System.in);
                String line = sc.nextLine();

                String[] msg = line.split(":");
                if (msg.length != 2) {
                    System.out.println("输入的格式不正确，请按照格式userId:message发送消息");
                    continue;
                }
                MessagePacket packet = new MessagePacket();
                packet.setMessage(msg[1]);
                packet.setSendTime(new Date());
                Channel channel = LoginUtils.getLoginUserChannel(msg[0]);
                if (channel == null) {
                    System.out.println("你要发送的用户没有上线，不能发送消息给(" + msg[0] + ")");
                    continue;
                }
                ByteBuf byteBuf = PacketCodec.INSTANCE.encoder(channel.alloc().buffer(), packet);
                channel.writeAndFlush(byteBuf);
                System.out.println("服务端想客户(" + msg[0] + ")发送了消息");
            }
        }).start();
    }
}
